<?php

namespace app\admin\controller\facrm\customer;

use app\admin\model\Admin;
use app\admin\model\AuthGroup;
use app\admin\model\facrm\Fields;
use app\common\controller\Backend;
use fast\Random;
use fast\Tree;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;


/**
 *客户管理
 */
class Index extends Backend
{

    protected $model = null;
    /**
     * 快速搜索时执行查找的字段
     */
    protected $searchFields = 'id,name,mobile,telephone';
    protected $childrenAdminIds = [];
    protected $noNeedRight = ['selectpage', 'getImportTpl'];
    protected $addon_config = array();
    private $expire_type = 0;
    protected $modelValidate = true;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\facrm\Customer();
        $this->addon_config = get_addon_config('facrm');
        $this->view->assign("levelList", $this->addon_config['level']);
        $this->view->assign("industryList", $this->addon_config['industry']);
        $this->view->assign("sourceList", $this->addon_config['source']);
        $this->view->assign("record_type_list", $this->addon_config['record_type']);
        $this->view->assign("addon_config", $this->addon_config);

        $this->request->filter(['strip_tags']);
    }

    /**
     * 客户列表
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        $scene = model('\app\admin\model\facrm\Scene');
        $scene_list = $scene->where('types', 'customer')
            ->where(function ($query) {
                $query->where('admin_id', 0)->whereor('admin_id', $this->auth->id);
            })
            ->column('id,name');

        if ($this->request->isAjax()) {
            $filter_w = $this->getFilterWhere($scene_list);
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                $this->request->request(['custom' => $filter_w]);
                return parent::selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $total = $this->model->getLoseWhere($this->addon_config, $this->expire_type)
                ->where($where)
                ->where($filter_w)
                ->with([
                    'createUser' => function ($user) {
                        $user->field('id,username,nickname');
                    },
                    'ownerUser' => function ($user) {
                        $user->field('id,username,nickname');
                    },
                ])
                ->order($sort, $order)->fetchSql(false)
                ->count();

            $list = $this->model->getLoseWhere($this->addon_config, $this->expire_type)
                ->where($where)
                ->where($filter_w)
                ->with([
                    'createUser' => function ($user) {
                        $user->field('id,username,nickname');
                    },
                    'ownerUser' => function ($user) {
                        $user->field('id,username,nickname');
                    },
                ])
                ->order($sort, $order)
                ->limit($offset, $limit)->fetchSql(false)
                ->select();

            if ($this->addon_config['show_contacts'] != 1) {
                $pattern = '/(\d{3})(\d{4})(\d{4})/i';
                $replacement = '$1****$3';
                //为了安全隐藏手机和电话
                foreach ($list as $row) {
                    $row->mobile = $row->mobile ? preg_replace($pattern, $replacement, $row->mobile) : '';
                    $row->telephone = $row->telephone ? preg_replace($pattern, $replacement, $row->telephone) : '';
                }
            }


            $result = array("total" => $total, "rows" => $list);
            return json($result);
        } else {
            $this->view->assign("scene_list", $scene_list);
        }

        /**
         * 自定义字段
         */
        $fields = \app\admin\model\facrm\Fields::getCustomFieldsTable('customer', [], 'isfilter=1 or islist=1');
        if ($fields) {
            $this->assignconfig('fields', json_encode($fields));
        }
        return $this->view->fetch();
    }

    /**
     * 处理过滤where条件
     * @return array
     */
    private function getFilterWhere($scene_list)
    {
        $filter = $this->request->get("filter", '');
        $filter = (array)json_decode($filter, true);
        $filter_w = [];
        $filter_w['owner_user_id'] = $this->auth->id;
        $filter['scene_id'] = isset($filter['scene_id']) ? $filter['scene_id'] : 1;
        if (isset($filter['scene_id'])) {

            if (!isset($scene_list[$filter['scene_id']])) {
                $this->error(__("您没有权限"));
            }
            switch ($filter['scene_id']) {
                case 1:
                    //全部客户
                    $this->childrenAdminIds = $this->auth->getChildrenAdminIds(true);
                    if ($this->childrenAdminIds)
                        $filter_w['owner_user_id'] = ['in', $this->childrenAdminIds];
                    break;
                case 2:
                    //我的客户
                    $filter_w['owner_user_id'] = $this->auth->id;
                    break;
                case 3:
                    //下属客户
                    $this->childrenAdminIds = $this->auth->getChildrenAdminIds(false);
                    if ($this->childrenAdminIds)//修复没有下属的时候获得公共客户
                        $filter_w['owner_user_id'] = ['in', $this->childrenAdminIds];
                    break;
                case 13:
                    $filter_w['owner_user_id'] = $this->auth->id;
                    $filter_w['rw_user_id'] = ['<>', ''];
                    break;
                case 14:
                    $filter_w[]=['exp',Db::raw("FIND_IN_SET('{$filter_w['owner_user_id']}',rw_user_id)")];
                    unset($filter_w['owner_user_id']);

                    break;
                default://其它的还做TODO
                    $filter_w['owner_user_id'] = $this->auth->id;
            }
            if (isset($filter['expire_type'])) {
                $this->expire_type = $filter['expire_type'];
                unset($filter['expire_type']);
            }
            unset($filter['scene_id']);
            $this->request->get(['filter' => json_encode($filter)]);
        }
        return $filter_w;
    }


    /**
     * 添加客户
     * @return mixed
     */
    public function add()
    {
        //判断是否有客户限制
        if ($this->addon_config['possess_num'] > 0 && $this->addon_config['possess_num'] <= $this->model->where('deal_status', 0)->where('owner_user_id', $this->auth->id)->count()) {
            $this->error(__("已经超过限制拥有客户数量,限制") . $this->addon_config['possess_num']);
        }
        if ($this->request->isPost()) {

            $params = $this->request->post("row/a");

            $params = array_merge($params, [
                'create_user_id' => $this->auth->id,
                'owner_user_id' => $this->auth->id,
                'province' => ($this->request->param('province')),
                'city' => ($this->request->param('city')),
                'area' => ($this->request->param('area')),
                'next_time' => strtotime($params['next_time']),
                'follow_time' => time(),
                'collect_time' => time(),
            ]);
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    $params = array_merge($params, [
                        'create_user_id' => $this->auth->id,
                        'owner_user_id' => $this->auth->id
                    ]);
                    \app\admin\model\facrm\Operatelog::setTitle(__('PC添加客户'));
                    $result = $this->model->add($params);
                    Db::commit();
                } catch (ValidateException $e) {

                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {

                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {

                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error($this->model->getError() ? __($this->model->getError()) : __('添加失败'));
                }
            }
            $this->error(__('参数不能为空', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 修改客户
     * @param null $ids
     */
    public function edit($ids = NULL)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $auth = new \addons\facrm\library\Auth();
        if (!$auth->checkCustomerAuth($row, $this->auth)) {
            $this->error(__('您没有权限管理该客户'));
        }

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $params = array_merge($params, [
                'province' => ($this->request->param('province')),
                'city' => ($this->request->param('city')),
                'area' => ($this->request->param('area')),
            ]);


            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    $result = $row->edit($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error($row->getError() ? __($row->getError()) : __('修改失败'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $payConfig = \addons\facrm\library\Order::getPayConfig();
        $this->assignconfig('payConfig', ($payConfig ? $payConfig['values'] : []));
        $this->view->assign("row", $row);
        return $this->view->fetch();

    }

    /**
     * 客户详情
     * @param null $ids
     * @return string
     * @throws Exception
     */
    public function detail($ids = NULL)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $auth = new \addons\facrm\library\Auth();
        if (!$auth->checkCustomerAuth($row, $this->auth)) {
            $this->error(__('您没有权限'));
        }
        $payConfig = \addons\facrm\library\Order::getPayConfig();
        $this->assignconfig('payConfig', ($payConfig ? $payConfig['values'] : []));
        $this->view->assign("row", $row);
        return $this->view->fetch('edit', ['action' => 'detail']);
    }

    /**
     * 删除
     * @param string $ids
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $pk = $this->model->getPk();
            $this->childrenAdminIds = $this->auth->getChildrenAdminIds(true);
            $list = $this->model->where($pk, 'in', $ids)->where('owner_user_id', 'in', $this->childrenAdminIds)->select();
            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
					\app\admin\model\facrm\Operatelog::setTitle(__('删除'));
                    $count += $v->del();
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    /**
     * 公海客户
     */
    public function common()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {

            $filter_w['owner_user_id'] = 0;
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $total = $this->model
                ->where($where)
                ->where($filter_w)
                ->with([
                    'createUser' => function ($user) {
                        $user->field('id,username,nickname');
                    },
                ])
                ->order($sort, $order)->fetchSql(false)
                ->count();
            $list = $this->model
                ->where($where)
                ->where($filter_w)
                ->with([
                    'createUser' => function ($user) {
                        $user->field('id,username,nickname');
                    },
                ])
                ->order($sort, $order)
                ->limit($offset, $limit)->fetchSql(false)
                ->select();
            foreach ($list as $row) {
                //公海为了安全隐藏手机和电话
                $row->mobile = "***";
                $row->telephone = "***";
            }

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 丢弃
     * @param null $ids
     */
    public function discard($ids = NULL)
    {
        $list = $this->model->where('id', 'in', $ids)->select();

        if (!$list) {
            $this->error(__('No Results were found'));
        }
        $this->childrenAdminIds = $this->auth->getChildrenAdminIds(true);
        $success_num = 0;//成功数量
        foreach ($list as $row) {
            if (!in_array($row['owner_user_id'], $this->childrenAdminIds)) {
                $this->error(__("您没有权限ID:{$row->id},成功放入公海{$success_num}条"));
            }
            $row->discard();
            $success_num++;
        }
        $this->success("成功放入公海{$success_num}条");
    }

    /**
     * 领取
     * @param null $ids
     */
    public function receive($ids = NULL)
    {
        $success_num = 0;//成功领取的数量
        $error_num = 0;//失败数量
        $error_ids = "";//失败的ids
        $msg = "";//返回消息

        Db::startTrans();
        try {
            $list = $this->model->where('id', 'in', $ids)->lock(true)->select();
            if (!$list) {
                \exception(__('No Results were found'));
            }
            foreach ($list as $row) {
                if ($row['owner_user_id']) {
                    $error_num++;
                    $error_ids = $error_ids ? $error_ids . "," . $row->id : $row->id;
                    continue;
                }
                //判断是否有客户限制
                if ($this->addon_config['possess_num'] > 0 && $this->addon_config['possess_num'] <= $this->model->where('deal_status', 0)->where('owner_user_id', $this->auth->id)->count()) {
                    $msg = __("已经超过限制拥有客户数量{$this->addon_config['possess_num']}条。成功领取{$success_num}条");
                    break;
                }

                $row->owner_user_id = $this->auth->id;
                $row->follow_time = $row->collect_time = time();
                \app\admin\model\facrm\Operatelog::setTitle(__('领取'));
                $row->save();
                //联系人负责人也更改
                $contacts = model('\app\admin\model\facrm\customer\Contacts');
                $contacts->where('customer_id', $row->id)->update(['owner_user_id' => $this->auth->id]);
                $success_num++;

            }
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $msg = $msg ? $msg : __("成功领取{:success_num}条,失败{:error_num}" . ($error_num ? ",失败ids:{:error_ids}" : ''),
            [
                'success_num' => $success_num,
                "error_num" => $error_num,
                'error_ids' => $error_ids
            ]);
        $this->success($msg);
    }

    /**
     * 转移客户
     * @param string $ids
     */
    public function divert($ids = NULL)
    {
        if (!$ids)
            $this->error(__("请选择客户"));
        if ($this->request->isPost()) {
            $admin_ids = $this->request->post("admin_id", '');
            $type = $this->request->post("type", '1');//分配方式


            if (!$admin_ids)
                $this->error(__("未选择员工"));

            $childrenAdminId = $this->childrenAdminIds = $this->auth->getChildrenAdminIds(true);
            $list = $this->model->where('id', 'in', $ids)->where(function ($query) use ($childrenAdminId) {
                $query->where('owner_user_id', 'in', $this->childrenAdminIds)->whereor('owner_user_id', 0);
            })->fetchSql(false)->select();

            //判断转移的员工是不是下属
            if (!in_array($admin_ids, $this->childrenAdminIds)) {
                $this->error(__('只能转移给自己或者下属'));
            }

            if (!$list) {
                $this->error(__('No Results were found'));
            }



            $contacts = model('\app\admin\model\facrm\customer\Contacts');
            $success_num = 0;//成功数量
            $admin_ids= explode(',',$admin_ids);//转成数组
            $admin_count=count($admin_ids);//管理员数量
            $i=0;//

            foreach ($list as $row) {
                if ($type==2){
                    //随机分配客户
                    $admin_id=$admin_ids[mt_rand(0, $admin_count - 1)];
                }else{
                    //平均分配
                    $admin_id=$admin_ids[$i];
                    $i==($admin_count-1)?$i=0:$i++;
                }

                $owner_count = $this->model->where('deal_status', 0)->where('owner_user_id', $admin_id)->count();


                if ($row->deal_status != 1) {//成交不占用数量
                    //判断是否有客户限制
                    if ($this->addon_config['possess_num'] > 0 && $this->addon_config['possess_num'] <= $owner_count) {
                        $this->error(__("已经超过限制拥有客户数量,限制") . $this->addon_config['possess_num'] . ",成功转移{$success_num}条!");
                    }
                    $owner_count++;
                }
                $row->owner_user_id = $admin_id;
                $row->collect_time = time();
                \app\admin\model\facrm\Operatelog::setTitle(__('转移客户给：%s', [$admin_id]));
                $row->save();
                //更改联系人
                //联系人负责人也更改
                $contacts->where('customer_id', $row->id)->update(['owner_user_id' => $admin_id]);

                $success_num++;


            }
            $this->success(__("成功转移{$success_num}条"));
        }

        return $this->view->fetch();

    }

    /**
     * selectpage
     * @Internal
     * @return \think\response\Json
     */
    public function selectpage()
    {
        $type = $this->request->param('type');
        $this->request->request(['showField' => 'name']);
        $this->request->request(['keyField' => 'id']);
        $this->request->request(['searchField' => array('name|id|mobile')]);
        if ($type == "all") {
            //显示的字段
            $this->request->request(['showField' => 'name', 'keyField' => 'id']);
            return parent::selectpage(); // TODO: Change the autogenerated stub
        } else {
            return $this->index();
        }

    }

    /**
     * 客户查重
     * @return string|\think\response\Json
     * @throws Exception
     */
    public function reduplicate()
    {
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            //$total = $this->model->where($where)->order($sort, $order)->fetchSql(false)->count();

            $list = $this->model
                ->where($where)
                ->with([
                    'createUser' => function ($user) {
                        $user->field('id,username,nickname');
                    },
                    'ownerUser' => function ($user) {
                        $user->field('id,username,nickname');
                    },
                ])
                ->field('id,name,deal_status,create_time,mobile,create_user_id,owner_user_id,telephone,update_time,tags')
                ->order($sort, $order)
                ->limit(10)//改成最多显示10条不给看有多少数据 ->limit($offset, $limit)
                ->select();

            $pattern = '/(\d{3})(\d{4})(\d{4})/i';
            $replacement = '$1****$3';
            //为了安全隐藏手机和电话
            foreach ($list as $row) {
                $row->mobile = $row->mobile ? preg_replace($pattern, $replacement, $row->mobile) : '';
                $row->telephone = $row->telephone ? preg_replace($pattern, $replacement, $row->telephone) : '';
            }
            $result = array("total" => count($list), "rows" => $list);
            return json($result);
        } else {
            return $this->view->fetch();
        }
    }

    /**
     * 合同列表
     */
    public function contractlist($customer_id)
    {
        //检查是否有权限
        $Auth = new  \addons\facrm\library\Auth();
        if (!$Auth->checkCustomerAuth($customer_id, $this->auth)) {
            $this->error(__("您没有权限查看合同"));
        }
        $this->searchFields = "id,number,name,remark";
        $this->model = model('\app\admin\model\facrm\Contract');
        $filter_w['customer_id'] = $customer_id;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        //如果发送的来源是Selectpage，则转发到Selectpage
        if ($this->request->request('keyField')) {
            $this->request->request(['custom' => $filter_w]);
            return parent::selectpage();
        }

        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        $total = $this->model
            ->where($where)
            ->where($filter_w)
            ->with([
            ])
            ->order($sort, $order)->fetchSql(false)
            ->count();
        $list = $this->model
            ->where($where)
            ->where($filter_w)
            ->with([
                'createUser' => function ($user) {
                    $user->field('id,username,nickname');
                },
                'orderAdmin' => function ($user) {
                    $user->field('id,username,nickname');
                },
                'customer' => function ($customer) {
                    $customer->field('id,name');
                },
            ])
            ->order($sort, $order)
            ->limit($offset, $limit)->fetchSql(false)
            ->select();
        $result = array("total" => $total, "rows" => $list);

        return json($result);
    }

    /**
     * 合同详情
     * @param $customer_id
     * @param null $ids
     * @return string|void
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function contract($customer_id = null, $ids = null)
    {
        $this->model = model('\app\admin\model\facrm\Contract');
        $filter_w['customer_id'] = $customer_id;
        $row = $this->model->where($filter_w)->find($ids);

        if (!$row) {
            $this->error(__('No Results were found'));
        }
        //检查是否有权限
        $Auth = new  \addons\facrm\library\Auth();
        if (!$Auth->checkCustomerAuth($row->customer, $this->auth)) {
            $this->error(__("您没有权限查看详情"));
        }

        $flow = model('\app\admin\model\facrm\Flow');
        $flow_r = $flow->where('types', 'contract')->where("status", 1)->find($row->flow_id);
        if ($this->request->isPost()) {
            //没有修改的权限
            $this->error(__("要修改合同请异步到合同管理！"));
        }
        $this->view->assign("row", $row);
        $this->view->assign("product_list", $row->product);
        $this->view->assign("flow", $flow_r);
        return $this->view->fetch('facrm/contract/index/edit');

    }


    /**
     * 回款列表
     */
    public function receivableslist($customer_id)
    {
        //检查是否有权限
        $Auth = new  \addons\facrm\library\Auth();
        if (!$Auth->checkCustomerAuth($customer_id, $this->auth)) {
            $this->error(__("您没有权限查看回款"));
        }
        $this->searchFields = "id,number,remark";
        $this->model = model('\app\admin\model\facrm\contract\Receivables');
        $filter_w['customer_id'] = $customer_id;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        //如果发送的来源是Selectpage，则转发到Selectpage
        if ($this->request->request('keyField')) {
            $this->request->request(['custom' => $filter_w]);
            return parent::selectpage();
        }

        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        $total = $this->model
            ->where($where)
            ->where($filter_w)
            ->order($sort, $order)->fetchSql(false)
            ->count();
        $list = $this->model
            ->where($where)
            ->where($filter_w)
            ->with([
                'createUser' => function ($user) {
                    $user->field('id,username,nickname');
                },
                'customer' => function ($customer) {
                    $customer->field('id,name');
                },
                'contract' => function ($customer) {
                    $customer->field('id,name,number');
                },
            ])
            ->order($sort, $order)
            ->limit($offset, $limit)->fetchSql(false)
            ->select();
        $result = array("total" => $total, "rows" => $list);

        return json($result);
    }

    /**
     * 回款详情
     * @param $customer_id
     * @param null $ids
     * @return string|void
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function receivables($customer_id = null, $ids = null)
    {
        $this->model = model('\app\admin\model\facrm\contract\Receivables');
        $filter_w['customer_id'] = $customer_id;
        $row = $this->model->where($filter_w)->find($ids);

        if (!$row) {
            $this->error(__('No Results were found'));
        }
        //检查是否有权限
        $Auth = new  \addons\facrm\library\Auth();
        if (!$Auth->checkCustomerAuth($row->customer, $this->auth)) {
            $this->error(__("您没有权限查看详情"));
        }
        $flow = model('\app\admin\model\facrm\Flow');
        $flow_r = $flow->where('types', 'receivables')->where('status', 1)->order('id desc')->find();

        $config = get_addon_config('facrm');
        $this->view->assign("account_list", $config['account']);
        if ($this->request->isPost()) {
            $this->error(__("请移步到回款管理上操作"));
        }
        $this->view->assign("row", $row);
        $this->view->assign("flow", $flow_r);
        return $this->view->fetch("facrm/contract/receivables/edit");


    }


    /**
     *批量导入客户
     */
    public function import()
    {
        $this->childrenGroupIds = $this->auth->getChildrenGroupIds(true);
        $this->groupList = $groupList = collection(AuthGroup::where('id', 'in', $this->childrenGroupIds)->select())->toArray();

        if ($this->request->isPost()) {
            $params = $this->request->param('row/a');

            if (!$params['file']) {
                $this->error(__('Parameter %s can not be empty', 'file'));
            }
            $filePath = ROOT_PATH . DS . 'public' . DS . $params['file'];

            if (!is_file($filePath)) {
                $this->error(__('No results were found'));
            }
            $owner_user_ids = [];
            //如果选择了组、没有选择成员 自动分配客户
            if (!$params['owner_user_id'] && $params['group_id']) {
                $childrenGroupIds = $this->auth->getChildrenGroupIds(true);
                Tree::instance()->init($this->groupList);
                $groupIds = Tree::instance()->getChildrenIds($params['group_id'], true);

                $authGroupList = \app\admin\model\AuthGroupAccess::
                field('uid,group_id')
                    ->where('group_id', 'in', $groupIds)
                    ->select();
                foreach ($authGroupList as $k => $v) {
                    if (in_array($v['uid'], $owner_user_ids)) continue;
                    $owner_user_ids[] = $v['uid'];
                }
                if (!$owner_user_ids) {
                    $this->error("没有数据");
                }
            } else {
                $owner_user_ids = explode(',', $params['owner_user_id']);
            }


            //实例化reader
            $ext = pathinfo($filePath, PATHINFO_EXTENSION);
            if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
                $this->error(__('Unknown data format'));
            }
            if ($ext === 'csv') {
                $file = fopen($filePath, 'r');
                $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
                $fp = fopen($filePath, "w");
                $n = 0;
                while ($line = fgets($file)) {
                    $line = rtrim($line, "\n\r\0");
                    $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                    if ($encoding != 'utf-8') {
                        $line = mb_convert_encoding($line, 'utf-8', $encoding);
                    }
                    if ($n == 0 || preg_match('/^".*"$/', $line)) {
                        fwrite($fp, $line . "\n");
                    } else {
                        fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                    }
                    $n++;
                }
                fclose($file) || fclose($fp);
                $reader = new \PhpOffice\PhpSpreadsheet\Reader\Csv();
            } elseif ($ext === 'xls') {
                $reader = new \PhpOffice\PhpSpreadsheet\Reader\Xls();
            } else {
                $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader("Xlsx");

            }

            $table = $this->model->getQuery()->getTable();
            $database = \think\Config::get('database.database');
            $fieldArr = [];
            $list = db()->query("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", [$table, $database]);
            foreach ($list as $k => $v) {

                $fieldArr[$v['COLUMN_COMMENT']] = $v['COLUMN_NAME'];
            }


            //加载文件
            $insert = 0;
            $fail_num = 0;
            $fail_row = [];
            try {
                if (!$PHPExcel = $reader->load($filePath)) {
                    $this->error(__('Unknown data format'));
                }
                $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
                $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
                $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
                $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
                $fields = [];
                for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
                    for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                        $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                        $fields[] = trim($val);//去掉左右空格
                    }
                }

                $admin_count = count($owner_user_ids);//员工数量
                $i = 0;//

                for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                    $values = [];
                    for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                        $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                        $values[] = is_null($val) ? '' : trim($val);
                    }
                    $row = [];
                    $temp = array_combine($fields, $values);
                    foreach ($temp as $k => $v) {
                        if (isset($fieldArr[$k]) && $k !== '') {
                            if (in_array($fieldArr[$k], $this->filter_column)) continue;
                            $row[$fieldArr[$k]] = trim($v);
                        }
                    }
                    //分配客户
                    if ((!isset($row['owner_user_id']) || $row['owner_user_id'] == '') && $owner_user_ids) {

                        if ($params['type'] == 2) {
                            //随机分配客户
                            $admin_id = $owner_user_ids[mt_rand(0, $admin_count - 1)];
                        } else {
                            //平均分配
                            $admin_id = $owner_user_ids[$i];
                            $i == ($admin_count - 1) ? $i = 0 : $i++;
                        }

                        $row['owner_user_id'] = $admin_id;
                    }
                    $row['create_user_id'] = $this->auth->id;

                    if ($row) {
                        $row['collect_time'] = time();
                        \app\admin\model\facrm\Operatelog::setTitle(__('导入客户'));
                        $result = $this->model->add($row);
                        if ($result) {
                            $insert++;
                        } else if (!$result && $params['skip'] != 1) {
                            \exception($this->model->getError() ? __($this->model->getError()) : __('添加失败'));
                        } else {
                            $row['error'] = $this->model->getError();
                            $fail_row[] = $row;
                            $fail_num++;
                        }
                    }


                }

            } catch (\Exception $exception) {
                $this->error($exception->getMessage() . "行数：" . $currentRow);
            } catch (ValidateException $e) {
                $this->error($e->getMessage() . "行数：" . $currentRow);
            }

            if ($fail_num) {
                $errpath = ($this->createExcel($fail_row, md5(Random::uuid())));
            }

            $return = ['insert' => $insert, 'fail_num' => $fail_num, 'errpath' => isset($errpath) ? $errpath : ''];
            $this->success(__("成功导入{:insert}条,失败{:fail_num}条",
                ['insert' => $insert, 'fail_num' => $fail_num, 'errpath' => isset($errpath) ? $errpath : '']),
                '', $return
            );

        }


        Tree::instance()->init($groupList);
        if ($this->auth->isSuperAdmin()) {
            $result = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0));
            foreach ($result as $k => $v) {
                $groupdata[$v['id']] = $v['name'];
            }
        } else {
            $result = [];
            $groups = $this->auth->getGroups();
            foreach ($groups as $m => $n) {
                $childlist = Tree::instance()->getTreeList(Tree::instance()->getTreeArray($n['id']));
                $temp = [];
                foreach ($childlist as $k => $v) {
                    $temp[$v['id']] = $v['name'];
                }
                $result[__($n['name'])] = $temp;
            }
            $groupdata = $result;
        }
        $groupdata[0] = '选择归属组';
        $this->view->assign('groupdata', $groupdata);
        return $this->view->fetch();
    }

    /**
     * 生成失败excel
     * @param unknown $data
     * @param unknown $batch
     * @param unknown $check_url
     */
    private function createExcel($data, $batch)
    {

        $pathname = (ROOT_PATH) . "/public/data/excel/";
        $path = $pathname . $batch . ".xls";
        if (is_file($path)) {
            return $path;
        }
        if (!is_dir($pathname)) {
            mkdir($pathname, 0755, true);
        }

        $table = $this->model->getQuery()->getTable();

        $database = \think\Config::get('database.database');
        $fieldArr = [];
        $list = db()->query("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", [$table, $database]);

        $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();
        $i = 0;
        $fieldArr = [];
        foreach ($list as $k => $v) {
            if (in_array($v['COLUMN_NAME'], $this->filter_column)) continue;
            if ($i >= 26) {
                $cell = chr(65 + $i / 26 - 1) . chr(65 + $i % 26);
            } else {
                $cell = chr(65 + $i);
            }
            $sheet->setCellValue($cell . '1', $v['COLUMN_COMMENT']);
            $i++;
            $fieldArr[$v['COLUMN_COMMENT']] = $v['COLUMN_NAME'];
        }
        $fieldArr['错误']="error";


        $j = 0;
        foreach ($data as $row){
            $i = 0;
            foreach ($fieldArr as $k => $v) {
                if ($i >= 26) {
                    $cell = chr(65 + $i / 26 - 1) . chr(65 + $i % 26);
                } else {
                    $cell = chr(65 + $i);
                }
                if ($v && isset($row[$v])) {
                    $sheet->setCellValue($cell . ($j + 2), $row[$v]);

                }
                $i++;
            }
            $j++;
        }



        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
        $writer->save($path);
        return "/data/excel/" . $batch . ".xls";;
    }


    /**
     * 需要过滤导入的字段
     * @var string[]
     */
    protected $filter_column = ['id', 'deal_status', 'deal_time', 'is_lock', 'delete_time', 'create_time', 'update_time', 'delete_time', 'collect_time'];

    /**
     * 获取导入模板
     * @throws PDOException
     * @throws \think\db\exception\BindParamException
     */
    public function getImportTpl()
    {

        $table = $this->model->getQuery()->getTable();

        $database = \think\Config::get('database.database');
        $fieldArr = [];
        $list = db()->query("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", [$table, $database]);

        $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();
        $i = 0;
        foreach ($list as $k => $v) {
            if (in_array($v['COLUMN_NAME'], $this->filter_column)) continue;
            if ($i >= 26) {
                $cell = chr(65 + $i / 26 - 1) . chr(65 + $i % 26);
            } else {
                $cell = chr(65 + $i);
            }
            $sheet->setCellValue($cell . '1', $v['COLUMN_COMMENT']);
            $i++;
        }

        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        //header('Content-Type:application/vnd.ms-excel');//输出03版本
        header("Content-Disposition: attachment;filename=customertpl" . date('Ymd') . '.xlsx');
        header('Cache-Control: max-age=0');
        header('Cache-Control: cache, must-revalidate');
        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
        try {
            $writer->save('php://output');
            $spreadsheet->disconnectWorksheets();
            unset($spreadsheet);
        } catch (\Exception $e) {
            echo $e->getMessage();
        }

        exit();

    }

    /**
     * 真实删除
     */
    public function destroy($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        $pk = $this->model->getPk();
        if ($ids) {
            $this->model->where($pk, 'in', $ids);
        }
        $count = 0;
        Db::startTrans();
        try {
            $list = $this->model->onlyTrashed()->select();
            foreach ($list as $k => $v) {
                $count += $v->trueDel();
            }
            Db::commit();
        } catch (PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        } else {
            $this->error(__('No rows were deleted'));
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }


    /**
     * 还原
     */
    public function restore($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        $pk = $this->model->getPk();
        if ($ids) {
            $this->model->where($pk, 'in', $ids);
        }
        $count = 0;
        Db::startTrans();
        try {
            $list = $this->model->onlyTrashed()->select();
            foreach ($list as $index => $item) {
                $count += $item->restores();
            }
            Db::commit();
        } catch (PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were updated'));
    }

    /**
     * 合并客户
     * @param string $ids
     */
    public function merge($ids = NULL)
    {
        if (!$ids)
            $this->error(__("请选择客户"));
        if ($this->request->isPost()) {
            $customer_id = $this->request->post("customer_id", '', 'intval');


            if (!$customer_id)
                $this->error(__("未选择目标客户"));
            $this->childrenAdminIds = $this->auth->getChildrenAdminIds(true);

            $list = $this->model->where('id', 'in', $ids)->where(function ($query) {
                $query->where('owner_user_id', 'in', $this->childrenAdminIds)->whereor('owner_user_id', 0);
            })->fetchSql(false)->select();

            if (!$list) {
                $this->error(__('No Results were found'));
            }

            //获取目标客户信息
            $customer = $this->model->where('id', $customer_id)->where(function ($query) {
                $query->where('owner_user_id', 'in', $this->childrenAdminIds)->whereor('owner_user_id', 0);
            })->fetchSql(false)->find();

            if (!$customer) {
                $this->error(__('目标客户信息不存在或者您没有权限'));
            }


            $contacts = model('\app\admin\model\facrm\customer\Contacts');
            $recordModel = model('\app\admin\model\facrm\Record');
            $recordFiles = model('\app\admin\model\facrm\record\Files');
            $businessModel = model('\app\admin\model\facrm\Business');
            $contractModel = model('\app\admin\model\facrm\Contract');
            $receivablesModel = model('\app\admin\model\facrm\contract\Receivables');


            $success_num = 0;//成功数量
            Db::startTrans();
            try {
                foreach ($list as $row) {
                    if ($customer->id == $row->id) {
                        continue;//合并客户和目标客户一样的时候处理方式
                    }

                    //联系人处理
                    $contacts->where('customer_id', $row->id)->update(['owner_user_id' => $customer->owner_user_id, 'customer_id' => $customer->id]);
                    //客户跟进记录处理
                    $recordModel->where('types', 'customer')->where('types_id', $row->id)->update(['types_id' => $customer->id]);
                    $recordFiles->where('types', 'customer')->where('types_id', $row->id)->update(['types_id' => $customer->id]);
                    //商机处理
                    $businessModel->where('customer_id', $row->id)->update(['owner_user_id' => $customer->owner_user_id, 'customer_id' => $customer->id]);

                    //合同处理
                    $contractModel->where('customer_id', $row->id)->update(['customer_id' => $customer->id]);
                    //收款处理
                    $receivablesModel->where('customer_id', $row->id)->update(['customer_id' => $customer->id]);
                    $customer->deal_status = $customer->deal_status ? $customer->deal_status : $row->deal_status;//成交状态
                    \app\admin\model\facrm\Operatelog::setTitle(__('合并客户：%s', [$row->id]));
                    $customer->update_time=time();
                    $customer->save();
                    $row->delete(true);
                    $success_num++;
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }

            if ($success_num) {
                $this->success(__("成功合并{$success_num}条"));
            }
            $this->error(__("没有合并任何数据"));

        }

        return $this->view->fetch();

    }

    /**
     * 下一个
     */
    public function next($type = 'owner')
    {
        $cachename = $this->auth->id . 'cachenextid';
        $prev_id = intval(cache($cachename));
        //自动获取我待跟进的客户
        if ($prev_id) {
            $this->model->where('id', '>', $prev_id);
        }
        switch ($type) {
            case 'all':
                $childrenAdminIds = $this->auth->getChildrenAdminIds(true);
                $this->model->where('owner_user_id', 'in', $childrenAdminIds);
                break;
            case 'owner';
            default:
                $this->model->where('owner_user_id', $this->auth->id);
        }


        $row = $this->model->where([function ($q) {
            return $q->where('next_time', '<>', '')->where('next_time', '<', time())->whereOr('follow_time', '');
        }])->fetchSql(false)->order('id asc')->field('id,name')->find();

        if (!$row) {
            cache($cachename, null);
            $this->error(__("没有下一个了"));
        }
        cache($cachename, $row->id);
        $this->success("", '', $row);
    }

    /**
     * 离职回收
     */
    public function recover(){
        //员工离职回收客户资料
        if ($this->request->isPost()) {
            $leave_user_id = $this->request->post("leave_user_id", '');
            $owner_user_ids = $this->request->post("owner_user_ids", '');
            $updateleave = $this->request->post("updateleave", '');

            $type = $this->request->post("type", '1');//分配方式


            if (!$leave_user_id)
                $this->error(__("未选择离职员工"));

            if (!$owner_user_ids)
                $this->error(__("未选择接受资料员工"));

            $this->childrenAdminIds =$this->auth->getChildrenAdminIds($this->auth->id, true);
            //判断转移的员工是不是下属
            if (array_diff_assoc(explode(',',$owner_user_ids), $this->childrenAdminIds)) {
                $this->error(__('只能转移给自己或者下属'));
            }
		
			$leave_user_id_arr=explode(',',$leave_user_id);
            if (array_diff_assoc($leave_user_id_arr, $this->childrenAdminIds)) {
                $this->error(__('只能操作自己的下属客户'));
            }
			
			if(in_array($this->auth->id,$leave_user_id_arr)){
				$this->error(__('不能操作自己'));
			}


            $list = $this->model->where('owner_user_id', 'in', $leave_user_id)->fetchSql(false)->select();


            if (!$list) {
                $this->error(__('该员工下面没有客户资料'));
            }
            $admin_ids= explode(',',$owner_user_ids);//转成数组
            $admin_count=count($admin_ids);//管理员数量
            $i=0;//
            $success_num = 0;//成功数量

            $contacts = model('\app\admin\model\facrm\customer\Contacts');
            foreach ($list as $row) {

                if ($type==2){
                    //随机分配客户
                    $admin_id=$admin_ids[mt_rand(0, $admin_count - 1)];
                }else{
                    //平均分配
                    $admin_id=$admin_ids[$i];
                    $i==($admin_count-1)?$i=0:$i++;
                }


               /* $owner_count = $this->model->where('deal_status', 0)->where('owner_user_id', $admin_id)->count();
                if ($row->deal_status != 1) {//成交不占用数量
                    //判断是否有客户限制
                    if ($this->addon_config['possess_num'] > 0 && $this->addon_config['possess_num'] <= $owner_count) {
                        $this->error(__("已经超过限制拥有客户数量,限制") . $this->addon_config['possess_num'] . ",成功转移{$success_num}条!");
                    }
                    $owner_count++;
                }*/
                $row->owner_user_id = $admin_id;
                $row->collect_time = time();
                \app\admin\model\facrm\Operatelog::setTitle(__('离职回收'));
                $row->save();
                //更改联系人
                //联系人负责人也更改
                $contacts->where('customer_id', $row->id)->update(['owner_user_id' => $admin_id]);
                $success_num++;
            }

            if ($updateleave){
                (new Admin())->where('id','in',$leave_user_id)->update(['status'=>'hidden']);
            }

            $this->success(__("成功回收客户资料{$success_num}条"));
        }


        return $this->view->fetch();

    }

    /**
     * 分享删除
     * @param string $ids
     */
    public function sdel($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $row = $this->model->where('id',  $ids)->find();
            //判断客户是不是属于当前用户
            if ($row->owner_user_id==$this->auth->id){
                //删除所有共享
                $row->rw_user_id="";
            }else{
                $rw_user_id=explode(',',$row->rw_user_id);
                $key = array_search($this->auth->id,$rw_user_id);

                if(isset($key)){
                    unset($rw_user_id[$key]);
                }else{
                    $this->error("该客户没有分享给你，无法删除分享");
                }

                $row->rw_user_id=implode(',',$rw_user_id);
            }
            \app\admin\model\facrm\Operatelog::setTitle(__('删除分享'));
            $row->save();
            $this->success("");
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));

    }


    /**
     * 分享客户
     * @param string $ids
     */
    public function share($ids = NULL)
    {
        if (!$ids)
            $this->error(__("请选择客户"));


        $row = $this->model->where('id',  $ids)->where('owner_user_id', $this->auth->id)->fetchSql(false)->find();

        if (!$row){
            $this->error(__("您不是该客户的负责人不能分享"));
        }

        if ($this->request->isPost()) {
            $admin_ids = $this->request->post("admin_id", '');
            if (!$admin_ids)
                $this->error(__("未选择要分享的同事"));

            $row->rw_user_id=$admin_ids;
            \app\admin\model\facrm\Operatelog::setTitle(__('分享给：%s', [$admin_ids]));
            $row->save();
            $this->success(__("分享成功"));
        }

        $this->view->assign('row',$row);

        return $this->view->fetch();

    }

    /**
     * 成交[非合同]
     * @param string $ids
     */
    public function deal($ids = NULL)
    {
        if (!$this->addon_config['deal']){
            $this->error(__("手动成交已经关闭，请打开或者添加合同"));
        }

        if (!$ids)
            $this->error(__("请选择客户"));
        $row = $this->model->where('id',  $ids)->fetchSql(false)->find();

        if (!$row)
            $this->error(__("客户信息为空"));

        $auth = new \addons\facrm\library\Auth();
        if (!$auth->checkCustomerAuth($row, $this->auth)) {
            $this->error(__('您没有权限管理该客户'));
        }

        if ($this->request->isPost()) {
            $money= $this->request->post("money", '');
            if (!$money||!is_numeric($money)||$money<=0)
                $this->error(__("请输入正确的金额"));

            $row->purchase_total+=$money;
            $row->purchase_times++;
            $row->deal_time=time();
            $row->deal_status=1;
            \app\admin\model\facrm\Operatelog::setTitle(__('成交￥%s', [$money]));
            $row->save();

            $this->success(__("成功"));
        }

        $this->view->assign('row',$row);

        return $this->view->fetch();

    }



}
